<?php
/**
 * Created by PhpStorm.
 * User: legend
 * Date: 2017/9/24
 * Time: 14:58
 */
namespace app\wechat;

use think\Controller;
use think\Session;
use think\Config;


class WxController extends Controller
{
    public $weixin_config;

    public function __construct()
    {
        $this->getWeixinConfig();
    }
    protected function getWeixinConfig()
    {
        $this->weixin_config['appid'] = Config::get('weixin.appid');
        $this->weixin_config['appsecret'] = Config::get('weixin.appsecret');
        $this->weixin_config['token'] = Config::get('weixin.token');
    }

    /**
     * 获取用户openid
     * @return mixed
     */
    public function GetOpenid()
    {
        if(Session::has('openid'))
            return Session::get('openid');
        //通过code获得openid
        if (!isset($_GET['code'])){
            //触发微信返回code码
            //$baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].str_replace('/index.php','',$_SERVER['PHP_SELF']).$_SERVER['QUERY_STRING']);
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
            $baseUrl = urlencode($http_type . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
            $url = $this->__CreateOauthUrlForCode($baseUrl);
            Header("Location: $url");
            exit();
        } else {
            //获取code码，以获取openid
            $code = $_GET['code'];
            $data = $this->getOpenidFromMp($code);
            //$_SESSION['openid'] = $data['openid'];
            Session::set('openid',$data['openid']);
            return $data;
        }
    }

    /**
     * 获取用户信息
     * @param $access_token
     * @param $openid
     * @return mixed
     */
    public function  GetUserInfo($access_token,$openid){
        $urlObj["access_token"] = $access_token;
        $urlObj["openid"] = $openid;
        $urlObj["lang"] = 'zh_CN';
        $bizString = $this->ToUrlParams($urlObj);
        $url = "https://api.weixin.qq.com/sns/userinfo?".$bizString;
        $res = $this->CurlExec($url);
        $data = json_decode($res,true);
        return $data;
    }

    /**
     * 构造获取code的url连接
     * @param string $redirectUrl 微信服务器回跳的url，需要url编码
     * @return 返回构造好的url
     */
    private function __CreateOauthUrlForCode($redirectUrl)
    {
        $urlObj["appid"] = $this->weixin_config['appid'];
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["response_type"] = "code";
//        $urlObj["scope"] = "snsapi_base";
        $urlObj["scope"] = "snsapi_userinfo";
        $urlObj["state"] = "STATE"."#wechat_redirect";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
    }

    /**
     * 通过code从工作平台获取openid机器access_token
     * @param string $code 微信跳转回来带上的code
     * @return openid
     */
    public function GetOpenidFromMp($code)
    {
        $url = $this->__CreateOauthUrlForOpenid($code);
        $res = $this->CurlExec($url);
        //取出openid
        $data = json_decode($res,true);
        //$this->data = $data;
        $openid = $data['openid'];
        return $data;
    }

    /**
     * 构造获取open和access_toke的url地址
     * @param string $code  微信跳转带回的code
     * @return 请求的url
     */
    private function __CreateOauthUrlForOpenid($code)
    {
        $urlObj["appid"] = trim($this->weixin_config['appid']);
        $urlObj["secret"] = trim($this->weixin_config['appsecret']);
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
    }

    /**
     * 拼接签名字符串
     * @param array $urlObj
     * @return 返回已经拼接好的字符串
     */
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign"){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }
    public function CurlExec($url){
        //初始化curl
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //运行curl，结果以json形式返回
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }
}